package com.sx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断请求是否是可以放过的某一个请求，或者在session中已经保存了登录状态的数据
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if(ignore(req) || req.getSession().getAttribute("u1")!=null){
            filterChain.doFilter(req,resp);
        }else {
            resp.sendRedirect("/login.jsp");
        }
    }

    private boolean ignore(HttpServletRequest req) {
        String[] uris = {"login","login.jsp","index.jsp"};
        for (String s : uris) {
            if(req.getRequestURI().endsWith(s)){
                System.out.println("true");
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
